<?php
/**
 * Yotaku
 * Copyright (c) 2016 http://www.yotaku.net All rights reserved.
 * Author: Creatint <creatint@163.com> <http://creatint.net>
 */
namespace Addons\Tags\Model;
use Think\Model;

class TagsModel extends Model{
    
    protected $error = null;

    /**
     * @describe 通过商品ID获取标签数据
     * @author Creatint
     * @param $goods_id
     * @return bool|mixed
     */
    public function get_tags_by_goods_id($goods_id, $field=true, $group=null){
        $map = array("goods_id"=>$goods_id);
        if($group){
            $res = $this->where($map)->group($group)->field($field)->select();
        }else{
            $res = $this->where($map)->field($field)->select();
        }
        if($res)
            return $res;
        else
            $this->error = "获取商品标签失败";
        return false;
    }


    public function clear_by_goods_id($goods_id){
        if(!($goods_id > 0))
            return false;
        $map = array("goods_id"=>$goods_id);
        $res = $this->where($map)->delete();
        return $res;
    }

    /**
     * @describe 保存标签数据
     * @author Creatint
     * @param $tags
     * @param $goods_id
     * @return bool
     */
    public function save_with_goods_id($tags, $goods_id){
        // 检查数据
        if(!is_array($tags) || !$goods_id){
            $this->error = "缺少标签数据或无商品ID";
            return false;
        }

        // 遍历标签数据
        foreach($tags as $v){

            // 检查标签 防止保存无效标签
            if(!$v["field"] || !$v["name"])
                continue;

            // 构造合法标签
            $data = array(
                "goods_id" => $goods_id,
                "field"     => $v["field"],
                "name"      =>  $v["name"],
                "value"     => $v["value"]
            );

            // 保存标签
            $this->add($data);
        }


        return true;
    }
    
    public function getError(){
        return $this->error;
    }
}